package com.coocaa.ops.api.base.third.media.source.service;

import com.alibaba.fastjson.JSONObject;
import com.coocaa.ops.api.base.third.media.source.feign.GetPolicyFeignClient;
import com.coocaa.ops.api.base.third.media.source.handler.HeaderHandler;
import com.coocaa.ops.api.common.enums.SourceTypeEnums;
import com.coocaa.ops.api.common.model.HeaderModel;
import com.coocaa.ops.common.tool.base.InstanceUtil;
import com.coocaa.ops.common.tool.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author bijiahao
 * @date : 2019/7/29.
 * @description 获取内容源
 */
@Service
@Slf4j
public class SourceService {

    @Autowired
    private GetPolicyFeignClient getPolicyFeignClient;

    /**
     * 获取内容源-根据请求头
     *
     * @param header
     * @return
     * 规则:
     * 1.请求自带source
     * 1.1 source匹配 --> voole变为yinhe
     * 1.2 source无法识别 --> 走媒资Api
     * 2.请求不带source
     * 2.1 从媒资服务获取成功 --> voole变为yinhe
     * 2.2 从媒资服务获取失败 --> tencent
     */
    public String getTvosSource(HeaderModel header) {
        String source = header.getSource();
        if (StringUtils.isEmpty(source)) {
            source = getSourceByHeader(header);
        }
        if (SourceTypeEnums.TENCENT.getValue().equals(source)) {
            source = SourceTypeEnums.TENCENT.getValue();
        } else if (SourceTypeEnums.YINHE.getValue().equals(source) || SourceTypeEnums.IQIYI.getValue().equals(source)) {
            source = SourceTypeEnums.YINHE.getValue();
        } else if (SourceTypeEnums.VOOLE.getValue().equals(source)) {
            source = SourceTypeEnums.YINHE.getValue();
        } else if (SourceTypeEnums.YOUKU.getValue().equals(source)) {
            source = SourceTypeEnums.YOUKU.getValue();
        } else {
            source = getSourceByHeader(header);
        }
        header.setSource(source);
        return source;
    }



    /**
     * 获取媒资策略
     *
     * @param header
     * @return
     */
    private String getSourceByHeader(HeaderModel header) {
        Map<String, String> headerMap = HeaderHandler.handlePackagingHeader(header);
        String jsonStr = getPolicyFeignClient.getPolicy(headerMap);
        try {
            String source = JSONObject.parseObject(jsonStr).getJSONObject("data").getString("source");
            return source;
        } catch (Exception e) {
            log.error("获取电视机所属影视源出错:" + jsonStr);
            Map<String, Object> errMap = InstanceUtil.newHashMap("MAC", header.getMac());
            throw new BusinessException(errMap, e.getMessage());
        }
    }

}